package com.cet.designpatterns.command;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @program: algorithm
 * @description:
 * @author: 陈恩涛
 * @create: 2021-09-18 10:02
 **/
public class RemoteController {
    /**
     * 开按钮的命令数组
     */
    private Command[] onCommands;

    /**
     * 关按钮的命令数组
     */
    private Command[] offCommands;

    /**
     * 执行撤销命令
     */
    private Command undoCommand;

    public RemoteController() {

        onCommands = new Command[5];
        offCommands = new Command[5];

        onCommands = Arrays.stream(onCommands)
                .map(command -> new NoCommand())
                .collect(Collectors.toList())
                .toArray(Command[]::new);

        offCommands = Arrays.stream(offCommands)
                .map(command -> new NoCommand())
                .collect(Collectors.toList())
                .toArray(Command[]::new);
    }

    /**
     * 给我们的按钮设置你需要的命令
     *
     * @param index
     * @param onCommand
     * @param offCommand
     */
    public void setCommand(int index, Command onCommand, Command offCommand) {
        onCommands[index] = onCommand;
        offCommands[index] = offCommand;
    }

    /**
     * 按下开按钮
     * @param index
     */
    public void onButtonPushed(int index) {
        onCommands[index].execute();

        //记录这次的操作用于撤销
        undoCommand = onCommands[index];
    }

    /**
     * 按下关按钮
     * @param index
     */
    public void offButtonPushed(int index) {
        offCommands[index].execute();

        //记录这次的操作用于撤销
        undoCommand = offCommands[index];
    }

    /**
     * 按下撤销按钮
     */
    public void undoButtonPushed() {
        undoCommand.undo();
    }
}
